package com.itlong.cloud.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.common.NettyServiceDTO;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.common.ParkingMessageDTO;
import com.itlong.cloud.POJO.DTO.common.ResultMessageDTO;
import com.itlong.cloud.POJO.VO.app.AppFloorDevicesVO;
import com.itlong.cloud.POJO.VO.app.AppPayParkFeeNoticeVO;
import com.itlong.cloud.POJO.VO.app.AppUserAndRoomInfoVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.common.network.ITCPServiceClient;
import com.itlong.cloud.common.network.tcp.netty.INettyServiceClient;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.property.ICloudIntercomServiceClient;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.iottp.IIotTpJPushClientServiceClient;
import com.itlong.cloud.paymenthub.IWeChatPayServiceClient;
import com.itlong.cloud.project.property.IParkCarHttpServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <desc>
 * 微信支付聚合Controller。
 * </desc>
 *
 * @createDate 2018/04/23
 */
@RestController
@RequestMapping("/wechatpay")
public class WeChatPayController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(WeChatPayController.class);

    @Autowired
    IWeChatPayServiceClient wechatPayServiceClient;

    @Autowired
    IParkCarHttpServiceClient parkCarHttpServiceClient;

    @Autowired
    INettyServiceClient nettyServiceClient;

    @Autowired
    private IIotTpJPushClientServiceClient iIotTpJPushClientServiceClient;

    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

    @Autowired
    ITCPServiceClient itcpServiceClient;

    @Autowired
    IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;

    @Autowired
    RedisService redisService;

    @Autowired
    ICloudIntercomServiceClient iCloudIntercomServiceClient;

    /**
     * <desc>
     * 微信支付结果回调通知
     * <desc/>
     *
     * @param
     * @return 商户后台逻辑处理后向微信后台响应SUCCESS的状态的String
     * @author Juguang.S
     * @createDate 2018/4/25
     */
    @ResponseBody
    @RequestMapping("/payResultNotice")
    public String payResultNotice(HttpServletRequest request) {
        try {
            String wechatReturnNotice = "<xml>\n" + "  <return_code><![CDATA[SUCCESS]]></return_code>\n" + "  <return_msg><![CDATA[OK]]></return_msg>\n" + "</xml>";
            System.out.print("微信支付回调获取数据开始");
            LOG.info("【微信支付回调获取数据开始】");

            String inputLine;
            String notityXml = "";

            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                request.getReader().close();
            } catch (Exception e) {
                LOG.info("xml获取失败：" + e);
                throw new Exception(e);
            }
            System.out.println("接收到的报文：" + notityXml);
            String projectId = "";
            AppPayParkFeeNoticeVO payParkFeeNoticeVO = wechatPayServiceClient.payResultNotice(notityXml);
            //如果deviceUnique不为空则需根据类型进行iot开门、iot呼梯或tcp开门
            String type = StringUtils.isNotEmpty(payParkFeeNoticeVO.getDeviceUnique())?payParkFeeNoticeVO.getDeviceUnique().substring(8,9):"";

            if(type.equals(PropertyEquipTypeEnum.ELEVATOR.getType().toString()) && payParkFeeNoticeVO.getMark()==0){
                //iot呼梯
                List<AppFloorDevicesVO> floors = iAppDeviceServiceClient.getFloorDevices(payParkFeeNoticeVO.getUserId(), payParkFeeNoticeVO.getProjectId(), 1);
                String deviceUniqueTmp = payParkFeeNoticeVO.getDeviceUnique();

                //检测用户是否有当前设备使用权限
                boolean isOne = floors.stream().filter(floorOne -> (floorOne != null) && (deviceUniqueTmp.equals(floorOne.getDeviceUnique()))).findFirst().isPresent();
                if (isOne) {  //当前用户有该设备权限
                    for (AppFloorDevicesVO floorInfo : floors) {
                        //是否有该电梯权限并做相应业务逻辑处理
                        if (floorInfo.getDeviceUnique().equals(deviceUniqueTmp)) {
                            // BigDecimal accountMoney = iAppPadFaceServiceClient.getUserAccountMoney(paymentDTO.getUId());
                            //取真实楼层
                            String realFloor = iAppHomeServiceClient.batchGetRealFloorList(deviceUniqueTmp, floorInfo.getLiveFloor());
                            if (StringUtils.isBlank(realFloor)) {
                                LOG.info(String.format("【平板_预约呼梯】楼层号信息有误，设备号：%s 楼层：s% ", deviceUniqueTmp, floorInfo.getLiveFloor()));
                            }
                            //调取IOT预约呼梯
                            iAppDeviceServiceClient.cloudElevatorCall(deviceUniqueTmp,
                                    CloudElevatorSourceEnum.ITLONG_CLOUD_ELEVATOR.getDescription(), "", "", realFloor,
                                    CloudElevatorCallTypeEnum.IN.getType(), null, CallElevatorSourceTypeEnum.APP.getType(),null,null,null, null, null,null, "");
                        }
                    }
                }
            }else if(type.equals(PropertyEquipTypeEnum.ENTRANCE.getType().toString()) && payParkFeeNoticeVO.getMark()==0){
                CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
                //IOT开门
                String deviceUnique = payParkFeeNoticeVO.getDeviceUnique();
                //查询门禁设备的iot账号及绑定的iot产品key
                Map<String,Object> entrance = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKey(deviceUnique);
                Map<String,Object> result = new HashMap<>();
                if(entrance != null && entrance.get("deviceUnique") != null) {
                    iCloudEntranceServiceClient.wippenOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                            Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                            CloudEntranceOpenTypeEnum.OPEN.getType().toString(), "1", entrance.get("productKey").toString(), payParkFeeNoticeVO.getUserId(),IotOpenDoorSourceEnum.ITLONG_TEMPORARY_PASS.getType().toString(),
                            null,null,  correlationId.getId(),"0",null);
                }
            }else if(type.equals(PropertyEquipTypeEnum.CLOUD_INTERCOM.getType().toString()) && payParkFeeNoticeVO.getMark()==0){
                //进行云对讲Tcp开门
                //云对讲设备信息
                String rooms = iAppDeviceServiceClient.getCloudIntercomRoomInfo(payParkFeeNoticeVO.getUserId(), projectId, payParkFeeNoticeVO.getDeviceUnique());
                iCloudIntercomServiceClient.iotOpenDoor(payParkFeeNoticeVO.getUserId(), payParkFeeNoticeVO.getDeviceUnique(), "squirrelunlock-idle-" + rooms, "1");
                LOG.info("【IOT云对讲开门】" + payParkFeeNoticeVO.getDeviceUnique() + "|" + payParkFeeNoticeVO.getUserId() + "|" + "squirrelunlock-idle-" + rooms);
            }
            //处理物业费缴费后向APP极光推送
            if(payParkFeeNoticeVO.getFeeType().equals("1")){
                Map<String,String> comands = new HashMap<>();
                comands.put("refreshSips","1");
                if(null != payParkFeeNoticeVO.getList() && !payParkFeeNoticeVO.getList().isEmpty()){
                    for(AppUserAndRoomInfoVO roomInfoVO : payParkFeeNoticeVO.getList()){
                        iIotTpJPushClientServiceClient.pushWithTaskTO(roomInfoVO.getProjectId(),roomInfoVO.getPhoneNum(),comands,"已缴费取消欠费联动app功能限制");
                    }
                }
            }

            //处理临时停车缴费通知
            NettyServiceDTO nettyServiceDTO = null;
            if(payParkFeeNoticeVO.getFeeType().equals("3")){
                nettyServiceDTO = parkCarHttpServiceClient.paymentParkFee(payParkFeeNoticeVO.getParkingCostsDTO());
                LOG.info("【临时车缴费后通知富士消息内容】："+nettyServiceDTO.toString());
                projectId=payParkFeeNoticeVO.getParkingCostsDTO().getProjectId();

            }
            //处理月卡车缴费通知
            if(payParkFeeNoticeVO.getFeeType().equals("4")){
                nettyServiceDTO = parkCarHttpServiceClient.carIssue(payParkFeeNoticeVO.getCarIssueDTO());
                projectId=payParkFeeNoticeVO.getCarIssueDTO().getProjectId();
            }
            if(nettyServiceDTO!=null){
                ResultMessageDTO resultMessageDTO = null;
                try{
                    nettyServiceClient.synOrderByParking(nettyServiceDTO.getClientKey(),nettyServiceDTO.getContent(),nettyServiceDTO.getParkingBusinessOrderEnum(),nettyServiceDTO.getMessageId());
                    int count = 0;
                    while (count < 10) {
                        Thread.sleep(500);
                        ParkingMessageDTO messageDTO = (ParkingMessageDTO)redisService.getObject(nettyServiceDTO.getMessageId(),ParkingMessageDTO.class);
                        if(messageDTO!=null) {
                            resultMessageDTO = JSON.parseObject(messageDTO.getContent(), ResultMessageDTO.class);
                            if (resultMessageDTO.getCode() != 0) {
                                if (payParkFeeNoticeVO.getFeeType().equals("3")) {
                                    wechatPayServiceClient.sendMessager(projectId, nettyServiceDTO.getContent(), ParkingOrderTypeEnum.PAYMENT_PARKING_FEE.getType());
                                }
                                if (payParkFeeNoticeVO.getFeeType().equals("4")) {
                                    wechatPayServiceClient.sendMessager(projectId, nettyServiceDTO.getContent(), ParkingOrderTypeEnum.CAR_ISSUE.getType());
                                }
                            }
                            break;
                        }
                        count++;
                    }
                }catch (Exception e){
                    //返回失败则将requestContent放入队列进行处理
                    if(payParkFeeNoticeVO.getFeeType().equals("3")){
                        wechatPayServiceClient.sendMessager(projectId,nettyServiceDTO.getContent(), ParkingOrderTypeEnum.PAYMENT_PARKING_FEE.getType());
                    }
                    if(payParkFeeNoticeVO.getFeeType().equals("4")){
                        wechatPayServiceClient.sendMessager(projectId,nettyServiceDTO.getContent(), ParkingOrderTypeEnum.CAR_ISSUE.getType());
                    }
                }
            }
            if (StringUtils.isNotBlank(payParkFeeNoticeVO.getRoomId())) {
                PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                padFaceSyncDataDTO.setOperateType("0");
                padFaceSyncDataDTO.setRoomId(payParkFeeNoticeVO.getRoomId());
                padFaceSyncDataDTO.setProjectId(payParkFeeNoticeVO.getProjectId());
                iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
            }
            return payParkFeeNoticeVO.getWechatReturnNotice();
        } catch (Exception e) {
            throw new DataAccessException("【App_微信支付】API返回的数据异常", e);
        }
    }

    /**
     * <desc>
     * 演示版微信支付结果回调通知
     * <desc/>
     *
     * @param
     * @return 商户后台逻辑处理后向微信后台响应SUCCESS的状态的String
     * @author Juguang.S
     * @createDate 2018/8/29
     */
    @ResponseBody
    @RequestMapping("/showPayResultNotice")
    public String showPayResultNotice(HttpServletRequest request) {
        try {
            System.out.print("微信支付回调获取数据开始");
            //LOG.info("微信支付回调获取数据开始");

            String inputLine;
            String notityXml = "";

            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                request.getReader().close();
            } catch (Exception e) {
                LOG.info("xml获取失败：" + e);
                throw new Exception(e);
            }
            System.out.println("接收到的报文：" + notityXml);
            return wechatPayServiceClient.showPayResultNotice(notityXml);
        } catch (Exception e) {
            throw new DataAccessException("【演示版App_微信支付】API返回的数据异常", e);
        }
    }

}
